import { isReferee } from "@/func";
import { WereWolfModule } from "@/werewolf/module";
import { WereWolfPlayer } from "@/werewolf/player";
import { ItemStack } from "@minecraft/server";
import { Game } from "@sapi-game/main";

interface NextToolOptions {
    onUse: (p: WereWolfPlayer) => void;
    shouldClear?: boolean;
    shouldClearAll?: boolean;
    getPlayers: () => WereWolfPlayer[];
}

export class WereWolfNextTool extends WereWolfModule.Component<NextToolOptions> {
    private nextId = "werewolf:next";

    override onAttach(): void {
        if (!this.options) return;
        //订阅使用事件
        this.subscribe(
            Game.events.itemUse,
            (t) => {
                const players = this.options!.getPlayers();
                const p = players.find((p) => p.id === t.source.id);
                if (p) {
                    this.options?.onUse(p);
                    //使用后清除物品
                    if (this.options?.shouldClear ?? true) {
                        p.clear(this.nextId);
                    }
                    //全部清除
                    if (this.options?.shouldClearAll ?? true) {
                        players.forEach((p) => p.clear(this.nextId));
                    }
                }
            },
            {
                itemId: this.nextId,
                players: this.context.players,
            }
        );
    }

    giveNextItemToReferee() {
        const referee = this.context.players.filter(
            (p) => p.player != undefined && isReferee(p.player)
        );
        referee.forEach((p) => {
            p.clear("werewolf:next");
            p.giveItem(new ItemStack("werewolf:next"));
        });
    }

    giveNextItemToAll() {
        const players = this.context.players.filter(
            (p) => p.player != undefined
        );
        players.forEach((p) => {
            p.clear("werewolf:next");
            p.giveItem(new ItemStack("werewolf:next"));
        });
    }

    clearAll() {
        const players = this.context.players.filter(
            (p) => p.player != undefined
        );
        players.forEach((p) => p.clear(this.nextId));
    }
}
